package gui.panel_new.evaluation.student;

import enums.PremisaTypeEnum;
import enums.TextBundleEnum;
import enums.URLEnum;
import gui.other.SylogismViewerDialog;
import gui.panel_new.evaluation.exeptions.ExerciseNotBuiltException;
import gui.panel_new.evaluation.exeptions.PunctuationZeroException;
import j_util.Utiles;
import misc.BundlesProvider;
import model.Polisilogismo;
import model.Sylogism;
import model.eval.TestExcercise;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ResourceBundle;
/*

    This file is part of Logica-Logike.

    Logica-Logike is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation version 3 of the License.

    Logica-Logike is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Logica-Logike.  If not, see <http://www.gnu.org/licenses/>.

 */
/**
 * Date: Sep 27, 2009
 * Time: 8:45:33 PM
 * @author Jose Martin Rozanec;
 */
public class SylogismViolationsPanel extends ExercisePanel {
    private javax.swing.JTextField conclusionField;
    private javax.swing.JLabel conclusionLabel;
    private javax.swing.JPanel cuadroPanel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JTextField premisaMayorField;
    private javax.swing.JLabel premisaMayorLabel;
    private javax.swing.JTextField premisaMenorField;
    private javax.swing.JLabel premisaMenorLabel;

    private JLabel addsPoints;
    private JLabel substractPoints;
    private JTextField addsPointsField;
    private JTextField substractPointsField;

    private JCheckBox violation1;
    private JCheckBox violation2;
    private JCheckBox violation3;
    private JCheckBox violation4;
    private JCheckBox violation5;
    private JCheckBox violation6;
    private JCheckBox violation7;
    private JCheckBox violation8;

    private ResourceBundle textBundle;

    private Sylogism sylogism;
    private boolean[] solutionArray;

    public SylogismViolationsPanel() {
        this.sylogism = new Sylogism();
        textBundle = BundlesProvider.getBundle(URLEnum.TEXT_BUNDLE);
        initComponents();
    }

    private void initComponents() {
        mainPanel = new javax.swing.JPanel();
        cuadroPanel = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        premisaMayorField = new javax.swing.JTextField();
        premisaMayorLabel = new javax.swing.JLabel();
        premisaMenorLabel = new javax.swing.JLabel();
        premisaMenorField = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        conclusionLabel = new javax.swing.JLabel();
        conclusionField = new javax.swing.JTextField();

        addsPoints = new JLabel(textBundle.getString(TextBundleEnum.SUMA.toString()));
        substractPoints = new JLabel(textBundle.getString(TextBundleEnum.RESTA.toString()));
        addsPointsField = new JTextField(7);
        addsPointsField.setEditable(false);
        substractPointsField = new JTextField(7);
        substractPointsField.setEditable(false);

        violation1 = new JCheckBox(textBundle.getString(TextBundleEnum.THREE_TERMS_VIOLATION.toString()));
        violation1.setBackground(Color.WHITE);
        addCheckBoxActionListener(violation1, 1);

        violation2 = new JCheckBox(textBundle.getString(TextBundleEnum.TERMINO_MAYOR_EXTENSION.toString()));
        violation2.setBackground(Color.WHITE);
        addCheckBoxActionListener(violation2, 2);

        violation3 = new JCheckBox(textBundle.getString(TextBundleEnum.TERMINO_MENOR_EXTENSION.toString()));
        violation3.setBackground(Color.WHITE);
        addCheckBoxActionListener(violation3, 3);

        violation4 = new JCheckBox(textBundle.getString(TextBundleEnum.TERMINO_MENOR_CONCLUSION.toString()));
        violation4.setBackground(Color.WHITE);
        addCheckBoxActionListener(violation4, 4);

        violation5 = new JCheckBox(textBundle.getString(TextBundleEnum.TERMINO_MEDIO_DOS_VECES.toString()));
        violation5.setBackground(Color.WHITE);
        addCheckBoxActionListener(violation5, 5);

        violation6 = new JCheckBox(textBundle.getString(TextBundleEnum.DOS_AFIRMATIVAS_CONCLUSION_NEGATIVA.toString()));
        violation6.setBackground(Color.WHITE);
        addCheckBoxActionListener(violation6, 6);

        violation7 = new JCheckBox(textBundle.getString(TextBundleEnum.DOS_POSITIVAS_NO_CONCLUSION_NEGATIVA.toString()));
        violation7.setBackground(Color.WHITE);
        addCheckBoxActionListener(violation7, 7);

        violation8 = new JCheckBox(textBundle.getString(TextBundleEnum.DOS_PREMISAS_PARTICULARES.toString()));
        violation8.setBackground(Color.WHITE);
        addCheckBoxActionListener(violation8, 8);

        mainPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
                new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true),
                textBundle.getString(TextBundleEnum.SILOGISMO.toString())));

        cuadroPanel.setBackground(new java.awt.Color(255, 255, 255));
        cuadroPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(
                new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true),
                textBundle.getString(TextBundleEnum.SILOGISMO.toString())));

        premisaMayorLabel.setText(Utiles.getFormattedString(
                textBundle.getString(TextBundleEnum.PREMISA_MAYOR.toString()), ""));
        premisaMayorLabel.setHorizontalTextPosition(SwingConstants.LEFT);
        premisaMayorLabel.setIcon(Utiles.createImageIcon(URLEnum.getReference(URLEnum.PREMISA_LARGO)));

        premisaMenorLabel.setText(Utiles.getFormattedString(
                textBundle.getString(TextBundleEnum.PREMISA_MENOR.toString()), ""));
        premisaMenorLabel.setHorizontalTextPosition(SwingConstants.LEFT);
        premisaMenorLabel.setIcon(Utiles.createImageIcon(URLEnum.getReference(URLEnum.PREMISA_LARGO)));

        jSeparator1.setForeground(new java.awt.Color(0, 0, 0));

        conclusionLabel.setText(Utiles.getFormattedString(
                textBundle.getString(TextBundleEnum.CONCLUSION.toString()), ""));
        conclusionLabel.setHorizontalTextPosition(SwingConstants.LEFT);
        conclusionLabel.setIcon(Utiles.createImageIcon(URLEnum.getReference(URLEnum.CONCLUSION_LARGO)));

        sizeTextFields();
        layoutComponents();
    }

    private void layoutComponents() {
        setBackground(Color.WHITE);
        setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        int x = 0;
        int y = 0;
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
        jPanel1.setLayout(new GridBagLayout());

        /*      PREMISAS     */
        jPanel1.add(premisaMayorLabel, gridBagConstraints);
//
//        gridBagConstraints.gridheight=3;
//        gridBagConstraints.gridwidth=2;
//        gridBagConstraints.gridx=7;
//        jPanel1.add(createScoringPanel(),gridBagConstraints);

        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridheight = 1;
        gridBagConstraints.gridwidth = 5;
        gridBagConstraints.gridx = 0;
        jPanel1.add(premisaMayorField, gridBagConstraints);

        gridBagConstraints.gridwidth = 1;

        gridBagConstraints.gridy = ++y;
        jPanel1.add(premisaMenorLabel, gridBagConstraints);

        gridBagConstraints.gridwidth = 5;
        gridBagConstraints.gridy = ++y;
        jPanel1.add(premisaMenorField, gridBagConstraints);

        gridBagConstraints.gridwidth = 6;
        gridBagConstraints.gridy = ++y;
        jSeparator1.setPreferredSize(new Dimension(620, 2));
        jPanel1.add(jSeparator1, gridBagConstraints);

        gridBagConstraints.gridwidth = 1;
        gridBagConstraints.gridy = ++y;
        jPanel1.add(conclusionLabel, gridBagConstraints);

        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridwidth = 5;
        jPanel1.add(conclusionField, gridBagConstraints);

//        jPanel1.setMinimumSize(new Dimension(655, 250));
//        jPanel1.setPreferredSize(new Dimension(655, 250));
        /*      END OF PREMISAS     */
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;//1
        add(jPanel1, gridBagConstraints);
//        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;//no estaba
        add(createScoringPanel(), gridBagConstraints);
        gridBagConstraints.gridy = 2;//1
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 2;
        add(createViolationsPanel(), gridBagConstraints);
        gridBagConstraints.gridy = 3;//1
        add(new JLabel(Utiles.createImageIcon(URLEnum.getReference(URLEnum.LOGIKE_BOTTOM_MEDIUM))),gridBagConstraints);
        premisaMayorField.setEditable(false);
        premisaMenorField.setEditable(false);
        conclusionField.setEditable(false);
    }

    private JPanel createViolationsPanel() {
        int y = 0;
        JPanel panel = new JPanel(new GridLayout(9, 1));
        panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createMatteBorder(1,0,0,0,Color.LIGHT_GRAY),
                textBundle.getString(TextBundleEnum.SYLOGISM_VIOLATIONS.toString())));
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        panel.add(new JLabel(textBundle.getString(TextBundleEnum.SELECT_SYLOGISM_VIOLATIONS.toString())),
                gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        panel.add(violation1, gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        panel.add(violation2, gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        panel.add(violation3, gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        panel.add(violation4, gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        panel.add(violation5, gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        panel.add(violation6, gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        panel.add(violation7, gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        panel.add(violation8, gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        panel.setMinimumSize(new Dimension(655, 250));//655
        panel.setPreferredSize(new Dimension(655, 250));
        panel.setBackground(Color.WHITE);
        return panel;
    }

    private JPanel createScoringPanel() {
        JPanel scoringPanel = new JPanel();
        scoringPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.LIGHT_GRAY),
                textBundle.getString(TextBundleEnum.PUNTAJE.toString())));
        scoringPanel.setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
//        scoringPanel.add(addsPoints, gridBagConstraints);
//        gridBagConstraints.gridx = 1;
//        scoringPanel.add(addsPointsField, gridBagConstraints);
//        gridBagConstraints.gridy = 1;
//        gridBagConstraints.gridx = 0;
//        scoringPanel.add(substractPoints, gridBagConstraints);
//        gridBagConstraints.gridx = 1;
//        scoringPanel.add(substractPointsField, gridBagConstraints);
        scoringPanel.add(addsPoints, gridBagConstraints);
        gridBagConstraints.gridx = 1;
        scoringPanel.add(addsPointsField, gridBagConstraints);
//        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridx = 2;
        scoringPanel.add(substractPoints, gridBagConstraints);
        gridBagConstraints.gridx = 3;
        scoringPanel.add(substractPointsField, gridBagConstraints);
        scoringPanel.setBackground(Color.WHITE);
        return scoringPanel;
    }

    private void sizeTextFields() {
        premisaMayorField.setColumns(57);//42
        premisaMayorField.setMinimumSize(new Dimension(500, 20));//new Dimension(450, 20));
        premisaMenorField.setColumns(57);//42
        premisaMenorField.setMinimumSize(new Dimension(500, 20));
        conclusionField.setColumns(57);//42
        conclusionField.setMinimumSize(new Dimension(500, 20));
    }

    private void analize() {//todo ver!
        //
    }

    public void setSylogism(Sylogism sylogism) {
        this.sylogism = sylogism;
        if (sylogism.getPremisa(PremisaTypeEnum.FIRST) != null) {
            premisaMayorField.setText(sylogism.getPremisa(PremisaTypeEnum.FIRST).toString());
        }
        if (sylogism.getPremisa(PremisaTypeEnum.SECOND) != null) {
            premisaMenorField.setText(sylogism.getPremisa(PremisaTypeEnum.SECOND).toString());
        }
        if (sylogism.getPremisa(PremisaTypeEnum.CONCLUSION) != null) {
            conclusionField.setText(sylogism.getPremisa(PremisaTypeEnum.CONCLUSION).toString());
        }
        analize();
    }

    public void setSolutionArray(boolean[] array) {
        this.solutionArray = array;
        checkStudentSolutionCheckBoxes(array);
    }

    private void checkStudentSolutionCheckBoxes(boolean[] array) {
        violation1.setSelected(array[0]);
        violation2.setSelected(array[1]);
        violation3.setSelected(array[2]);
        violation4.setSelected(array[3]);
        violation5.setSelected(array[4]);
        violation6.setSelected(array[5]);
        violation7.setSelected(array[6]);
        violation8.setSelected(array[7]);
    }

    protected void setSaveActionListener() {
        class SaveSylogismAction extends AbstractAction {
            public SaveSylogismAction() {
                super("", Utiles.createImageIcon(URLEnum.getReference(URLEnum.SAVE_AS)));
            }

            public void actionPerformed(ActionEvent e) {
                if (!sylogism.isComplete()) {
                    JOptionPane.showMessageDialog(SylogismViolationsPanel.this,
                            textBundle.getString(TextBundleEnum.WARNING_NO_GUARDAR_SILOGISMO_VACIO.toString()),
                            "", JOptionPane.WARNING_MESSAGE);
                } else {
                    String path = "";
//                    int state = fileChooser.showSaveDialog(SylogismViolationsPanel.this);
//                    if (state == JFileChooser.APPROVE_OPTION) {
//                        path = fileChooser.getSelectedFile().getPath();
//                        Utiles.saveTextFileAlertingOverwrite(path, ".xml", sylogism.toXML());
//                    }
                }
            }
        }
//        saveButton.setAction(new SaveSylogismAction());
    }

    protected void setSaveButtonEnabled() {
//        saveButton.setEnabled(true);
    }

    protected void setOpenActionListener() {
        class OpenSylogismAction extends AbstractAction {
            public OpenSylogismAction() {
                super("", Utiles.createImageIcon(URLEnum.getReference(URLEnum.OPEN)));
            }

            public void actionPerformed(ActionEvent e) {
                String path = "";
                int state = 0;
//                        fileChooser.showOpenDialog(SylogismViolationsPanel.this);
                if (state == JFileChooser.APPROVE_OPTION) {
//                    path = fileChooser.getSelectedFile().getPath();
                    try {
                        RandomAccessFile randomAccessFile = new RandomAccessFile(path, "r");
                        String xml = randomAccessFile.readUTF();

                        if (xml.startsWith(Sylogism.openTag())) {
                            setSylogism(Sylogism.parseXML(xml));
                        } else {
                            if (xml.startsWith(Polisilogismo.openTag())) {
                                SylogismViewerDialog sylogismViewerDialog = new SylogismViewerDialog(
                                        Polisilogismo.parseXML(xml).getIterator());
                                Utiles.centerDialog(sylogismViewerDialog);
                                sylogismViewerDialog.setSize(337, 160);
                                sylogismViewerDialog.setResizable(false);
                                sylogismViewerDialog.setModal(true);
                                sylogismViewerDialog.setVisible(true);
                                if (sylogismViewerDialog.accepted()) {
                                    setSylogism(sylogismViewerDialog.getSylogism());
                                }
                            } else {
                                JOptionPane.showMessageDialog(SylogismViolationsPanel.this,
                                        textBundle.getString(TextBundleEnum.WARNING_ARCHIVO_INCORRECTO_SILOGISMO.toString()));
                            }
                        }
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
//        openButton.setAction(new OpenSylogismAction());
    }

    protected void setOpenButtonEnabled() {
//        openButton.setEnabled(true);
    }

    protected void setFocusOnComponent() {
        //remains unimplemented...
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("SylogismViolationsPanel");
        frame.setContentPane(new SylogismViolationsPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public TestExcercise getExercise() throws ExerciseNotBuiltException, PunctuationZeroException {
        if (!sylogism.isComplete() || addsPointsField.getText().equals("") ||
                substractPointsField.getText().equals("")) {
            throw new ExerciseNotBuiltException();
        }
        if (Integer.parseInt(addsPointsField.getText()) == 0) {
            throw new PunctuationZeroException();
        }
        testExercise.setStudentsSolution(solutionArray);
        return testExercise;
    }

    public void setExercise(TestExcercise testExerciseData) {
        testExercise = testExerciseData;
        setSylogism((Sylogism) testExercise.getExcerciseData());
        setSolutionArray((boolean[]) testExercise.getStudentsSolution());
        addsPointsField.setText("" + testExercise.getCorrectScore());
        substractPointsField.setText("" + testExercise.getIncorrectScore());
    }

    private void addCheckBoxActionListener(final JCheckBox checkBox, final int violation) {
        checkBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                solutionArray[violation - 1] = checkBox.isSelected();
                testExercise.setStudentsSolution(solutionArray);
            }
        });
    }
}
